package com.wowangz.cms.user.api;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.CommonCrypto;
import com.wowangz.cms.common.utils.DataFormat;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.user.pojo.User;
import com.wowangz.cms.user.service.UserService;

/**
 * Controller
 *
 * @author auto
 */
@Scope("prototype")
@Controller
@SuppressWarnings("unchecked")
public class UserController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	@RequestMapping(value = "/systemmanage/user/addUser.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = null;
		try {
			user = (User) ServletUtils.getParametersToBaseEntity(request, User.class);
			UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, true);
			user.setInputtime(new Date());
			user.setInputuserid(userContext.getLoginUser().getId());
			user.setModifytime(new Date());
			user.setModifyuserid(userContext.getLoginUser().getId());
			user.setStatusid(SysConstant.RecordStatus.VALID);
			user.setCheckstatus(SysConstant.CheckStatus.SAVE);
			String passwordSHA = CommonCrypto.encryptSHAEncoder(user.getPassword(), user);
			user.setPassword(passwordSHA);
			userService.add(user);
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		}
		return "/WEB-INF/jsp/systemmanage/authoritymanage/userList";
	}

	@RequestMapping(value = "/systemmanage/user/deleteUser.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			String userId = request.getParameter("id");
			UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
			userService.delete(userId);
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		}
	}

	/**
	 *
	 * @描述：修改密码
	 * @author HUANGYUAN
	 * @TIME:2015年8月28日 上午11:38:51
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/systemmanage/user/modify.json", method = RequestMethod.POST)
	public void modifyPassword(HttpServletRequest request, HttpServletResponse response) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		String userid = request.getParameter("id");
		User user = new User();
		try {
			if (StringUtils.isNotEmpty(userid)) {
				UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
				String passwordSHA = CommonCrypto.encryptSHAEncoder("123456");
				user.setPassword(passwordSHA);
				user.setId(new Long(userid));
				userService.update(user);
				getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "systemmanage.user.spassword.update.success"));
			} else {
				getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.user.spassword.update.success"));
			}

		} catch (ServiceException e) {
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.user.spassword.update.success"));
			e.printStackTrace();
		} catch (NumberFormatException e) {
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.user.spassword.update.success"));
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 *
	 * @描述： 跳转到列表页面
	 * @author HUANGYUAN
	 * @TIME:2015年8月28日 上午11:39:11
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/user/queryUserList.web")
	public String queryUserList(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/authoritymanage/userList";
	}

	/**
	 *
	 * @描述：获得列表的数据
	 * @author HUANGYUAN
	 * @TIME:2015年8月28日 上午11:39:32
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/user/queryUserListInfoDataGrid.json", method = RequestMethod.POST)
	public void queryUserListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			String checkstatus = (String) map.get("checkstatus");
			if ("0".equals(checkstatus)) {
				map.remove("checkstatus");
			}

			UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
			long resultCount = userService.findResultCount(map);
			List<User> resultList = userService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("userno", DataTypeConstant.STRING);
			dataStyle.addDepict("loginname", DataTypeConstant.STRING);
			dataStyle.addDepict("username", DataTypeConstant.STRING);
			dataStyle.addDepict("validstart", DataTypeConstant.DATE);
			dataStyle.addDepict("validend", DataTypeConstant.DATE);
			dataStyle.addDepict("inputname", DataTypeConstant.STRING);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			// dataStyle.addDepict("checkstatus", DataTypeConstant.LONG);
			dataStyle.addDepictByFunction("checkstatus", SysConstant.CheckStatus.class, "getName", new Class[] { long.class });

			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 * @描述： 跳转到新增页面
	 * @author HUANGYUAN
	 * @TIME:2015年8月28日 上午11:39:46
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/user/toAddUser.web")
	public String toAddUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/authoritymanage/userAdd";
	}

	/**
	 *
	 * @描述：跳转到修改用户信息的页面
	 * @author HUANGYUAN
	 * @TIME:2015年8月28日 上午11:40:09
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/user/toUpdateUser.web")
	public String toUpdateUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String userId = getRequest().getParameter("userid");
			UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
			User user = userService.findUserById(userId);
			// 设置有效期的结束时间
			user.setValidend(user.getValidend());
			model.addAttribute("user", user);
			model.addAttribute("validstart", DataFormat.formatDate(user.getValidstart(), DataFormat.DT_YYYY_MM_DD));
			model.addAttribute("validend", DataFormat.formatDate(user.getValidend(), DataFormat.DT_YYYY_MM_DD));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/authoritymanage/userUpdate";
	}

	/**
	 *
	 * @描述：修改用户信息
	 * @author HUANGYUAN
	 * @TIME:2015年8月28日 上午11:41:16
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/user/updateUser.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = null;
		try {
			user = (User) ServletUtils.getParametersToBaseEntity(request, User.class);
			UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
			user.setCheckstatus(SysConstant.CheckStatus.SAVE);
			user.setModifytime(new Date());
			user.setModifyuserid(userContext.getLoginUser().getId());
			userService.update(user);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		}
		return "/WEB-INF/jsp/systemmanage/authoritymanage/userList";
	}

	/**
	 *
	 * @描述：校验用户是否存在
	 * @author HUANGYUAN
	 * @TIME:2015年8月28日 上午11:41:28
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/user/validattionUser.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validattionCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		User user = null;
		try {
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			user = (User) ServletUtils.getParametersToBaseEntity(request, User.class);
			UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);

			map.put("statusid", SysConstant.RecordStatus.VALID);
			if (null != user.getId()) {
				map.put("id", user.getId());
			}
			map.put("userno", user.getUserno());
			// 查找用户是否存在
			if (!userService.validationUser(map)) {
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.User.check.userno"));
			}
			map.remove("userno");
			map.put("loginname", user.getLoginname());
			if (!userService.validationUser(map)) {
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.User.check.loginname"));
			}
			map.remove("loginname");

			if (StringUtils.isNotEmpty(errorMsg.toString())) {
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
